home *** CD-ROM | disk | FTP | other *** search
/ Cream of the Crop 1 / Cream of the Crop 1.iso / PROGRAM / SNIP0492.ARJ / BITCNT_2.C < prev    next >
C/C++ Source or Header  |  1991-09-23  |  728b  |  34 lines

  1. int bitcount(long i)
  2. {
  3.       i = ((i & 0xAAAAAAAA) >>  1) + (i & 0x55555555);
  4.       i = ((i & 0xCCCCCCCC) >>  2) + (i & 0x33333333);
  5.       i = ((i & 0xF0F0F0F0) >>  4) + (i & 0x0F0F0F0F);
  6.       i = ((i & 0xFF00FF00) >>  8) + (i & 0x00FF00FF);
  7.       i = ((i & 0xFFFF0000) >> 16) + (i & 0x0000FFFF);
  8.       return (int)i;
  9. }
  10.  
  11. #ifdef TEST
  12.  
  13. #include <stdio.h>
  14. #include <stdlib.h>
  15.  
  16. #define plural_text(n) &"s"[(1 == (n))]
  17.  
  18. void main(int argc, char *argv[])
  19. {
  20.       long n;
  21.  
  22.       while(--argc)
  23.       {
  24.             int i;
  25.  
  26.             n = atol(*++argv);
  27.             i = bitcount(n);
  28.             printf("%ld contains %d bit%s set\n",
  29.                   n, i, plural_text(i));
  30.       }
  31. }
  32.  
  33. #endif /* TEST */
  34.